import {
  Decoration,
  ViewPlugin,
  MatchDecorator,
  EditorView,
  WidgetType,
} from "@codemirror/view";

class LogicalOperatorWidget extends WidgetType {
  constructor(name) {
    super();
    this.name = name;
  }

  eq(other) {
    return this.name == other.name;
  }

  toDOM() {
    let element = document.createElement("span");
    element.style.cssText = `
            font-size: 14px;
            color: #ee62d5;
    `;
    element.textContent = this.name;
    return element;
  }

  ignoreEvent() {
    return false;
  }
}

const logicalOperatorMatcher = new MatchDecorator({
  regexp: /[且或]/g,
  decoration: (match) => {
    return Decoration.replace({
      widget: new LogicalOperatorWidget(match[0]),
    });
  },
});

export const logicalOperatorPlugin = ViewPlugin.fromClass(
  class {
    logicalOperators;

    constructor(view) {
      this.logicalOperators = logicalOperatorMatcher.createDeco(view);
    }

    update(update) {
      this.logicalOperators = logicalOperatorMatcher.updateDeco(
        update,
        this.logicalOperators
      );
    }
  },
  {
    decorations: (instance) => instance.logicalOperators,
    provide: (plugin) =>
      EditorView.atomicRanges.of((view) => {
        return view.plugin(plugin)?.logicalOperators || Decoration.none;
      }),
  }
);
